<template>
  <div style="padding: 10px;">
    <el-row >
      <el-col>
        <div style="display: flex;">
          <div>
<!--            <el-button type="primary">查询</el-button>-->
            <el-form :model="list_params" ref="searchForm"  size="small" :inline="true" @submit.native.prevent="() => handleQuery()">
              <el-form-item label="" label-width="80px" prop="name">
                <el-input v-model="list_params.name" placeholder="搜索档口名称" ></el-input>
              </el-form-item>
              <el-form-item>
                <el-select filterable  filterable v-model="list_params.marketId" placeholder="请选择所属市场" clearable :style="{width: '100%'}">
                  <el-option v-for="market in market_data" :key="market.id" :label="market.name"
                             :value="market.id"  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary"  size="mini" native-type="submit">搜索</el-button>
                <el-button  size="mini" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
          <div style="flex: 1;"></div>
          <div>
<!--            <el-button>删除</el-button>-->
            <el-button @click="handleEnable(1)" >禁用</el-button>
            <el-button @click="handleEnable(0)" >启用</el-button>
            <!-- <el-button @click="handleExport">导出</el-button>
            <el-button>导入</el-button> -->
            <el-button type="primary" @click="addCustom" >新增</el-button>
          </div>
        </div>
      </el-col>
      <el-col>
        <div style="margin-top: 10px;">
          <el-table :data="table_data" @selection-change="handleSelectionChange" :height="table_height">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column label="ID" prop="id"></el-table-column>
            <el-table-column label="档口名称" prop="name"></el-table-column>
            <el-table-column label="主营品种" prop="customerNum"></el-table-column>
            <el-table-column label="所属市场" prop="marketName"></el-table-column>
            <el-table-column label="手机号码" prop="phoneNumber"></el-table-column>
            <el-table-column label="应收余额" >-</el-table-column>
            <el-table-column label="预收款余额" >-</el-table-column>
            <el-table-column label="授权状态" width="80" prop="accreditStatus">
              <template slot-scope="scope" >
                {{scope.row.accreditStatus==1?'已授权':'未授权'}}
              </template>
            </el-table-column>
            <el-table-column label="最后登录时间" prop="createTime" width="160"></el-table-column>
            <el-table-column label="创建时间" prop="createTime" width="160"></el-table-column>
            <el-table-column label="状态" width="60" >
              <template slot-scope="scope" >
              <div style="color: #111928;" v-if="scope.row.enable==0" >启用</div>
              <div style="color: #EB4646;" v-else >禁用</div>
              </template>
            </el-table-column>
            <el-table-column label="操作">

              <template slot-scope="scope" >
                <el-popconfirm title="确定对该档口授权进行操作？"
                               @confirm="accredit(scope.row)">
                  <el-button slot="reference"
                    size="mini"
                    type="text"
                  >{{scope.row.accreditStatus==1?'取消授权':' 授权'}}</el-button>
                </el-popconfirm>
              <el-button
                size="mini"
                type="text"
                @click="editInfo(scope.row)"

              >编辑</el-button>
              <el-popconfirm
                title="确定要删除这条记录吗？"
                @confirm="del_item(scope.row)"
              >
                <el-button
                  slot="reference"
                  size="mini"
                  type="text"

                >删除</el-button>
              </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="list_total>0"
            :total="list_total"
            :page.sync="list_params.pageNum"
            :limit.sync="list_params.pageSize"
            @pagination="getList"
          />
        </div>
      </el-col>
    </el-row>
    <el-dialog  :visible.sync="add_custom_dialog_show" title="添加客户" width="680px" style="border-radius: 10px;" @close="close">
      <el-form  ref="elForm" :model="formData" :rules="rules" size="medium" label-width="100px">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phoneNumber">
              <el-input v-model="formData.phoneNumber" placeholder="请输入手机号码"  show-word-limit clearable
                         :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="登录密码" prop="pwd">
              <el-input v-model="formData.password" placeholder="请输入登录密码"  show-word-limit clearable
                        :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="档口名称" prop="name">
              <el-input v-model="formData.name" placeholder="请输入档口名称"  show-word-limit clearable
                        :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="主营品种" prop="mainVariety">
              <el-input v-model="formData.mainVariety" placeholder="请输入主营品种"  show-word-limit clearable
                        :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属市场" prop="marketId">
              <el-select filterable  filterable v-model="formData.marketId" placeholder="请选择所属市场" clearable :style="{width: '100%'}">
                <el-option v-for="market in market_data" :key="market.id" :label="market.name"
                           :value="market.id"  ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="档口地址" prop="city">
<!--              <treeselect-->
<!--                v-model="formData.city"-->
<!--                :options="area_data"-->
<!--                :show-count="true"-->
<!--                placeholder="请选择所在城市"-->
<!--              />-->
              <el-cascader style="width: 100%;" :lazy="true" v-model="formData.city" :options="area_data" :props="{value:'id'}" :show-all-levels="false"></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="详细地址" prop="address">
              <el-input v-model="formData.address" placeholder="请输入详细地址" clearable
                        :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="档口类型" prop="stallType">
              <el-radio-group v-model="formData.stallType">
                <el-radio :label="0">个人</el-radio>
                <el-radio :label="1">企业</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="企业名称" prop="enterpriseName">
              <el-input v-model="formData.enterpriseName" placeholder="请输入企业名称" clearable
                        :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经办人姓名" prop="agentName">
              <el-input v-model="formData.agentName" placeholder="请输入经办人姓名" clearable
                        :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经办人手机号" prop="agentPhone">
              <el-input v-model="formData.agentPhone" placeholder="请输入经办人手机号" clearable
                        :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经办人身份证" prop="agentIdCard">
              <el-input v-model="formData.agentIdCard" placeholder="请输入经办人身份证" clearable
                        :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="付款条款" prop="paymentTerms">
              <el-input  v-model="formData.paymentTerms"  placeholder="请输入付款条款"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input type="textarea" v-model="formData.remark"></el-input>
            </el-form-item>
          </el-col>
<!--          <el-col :span="24">-->
<!--            <el-form-item label="上传" prop="pictures" >-->
<!--              <el-upload ref="field101" :file-list="pictures" :action="uploadImgUrl"-->
<!--                         :headers="headers"-->
<!--                         :before-upload="field101BeforeUpload" list-type="picture-card" accept="image/*">-->
<!--                <i class="el-icon-plus"></i>-->
<!--              </el-upload>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
          <el-col :span="24">
            <el-form-item label="是否启用" prop="data_enable">
              <el-switch v-model="formData.enable" :active-value="0" :inactive-value="1"  ></el-switch>
            </el-form-item>
          </el-col>
          <el-col>
            <div style="background: #F6F6F6;margin:0px -20px;height: 40px;line-height: 40px;padding: 0px 33px;display: flex;justify-content: space-between;margin-bottom: 20px;">
              <div>结算账户信息</div>
              <div>收起</div>
            </div>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开户银行" prop="depositBank">
              <el-input v-model="formData.depositBank"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开户名" prop="accountName">
              <el-input v-model="formData.accountName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="银行账号" prop="account">
              <el-input v-model="formData.account"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="title" style="background: #F3F4F6;margin: -20px;padding: 20px;height: 58px;border-radius: 10px;">{{formData.id?'编辑档口':'新增档口'}}</div>
      <div slot="footer"  >
        <el-button @click="close"  >取消</el-button>
        <el-button type="primary"  @click="handleConfirm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { list,add,handleEnable,detail,update,handleAccredit,del } from "@/api/base/stall";
import { list as marketList } from "@/api/base/market";
import { getAreaTree } from '@/api/common'
import { getToken } from "@/utils/auth";
import { mapGetters } from 'vuex'
import store from '@/store'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: 'custom',
  dicts:['customer_classify'],
  components: { Treeselect },
  ...mapGetters([
    'user_id'
  ]),
  data() {
    return {
      table_height:window.innerHeight - 300,
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      add_custom_dialog_show:false,
      edit_custom_dialog_show:false,
      table_data:[],
      area_data:[],
      formData:{
        name:'',
        phoneNumber:'',
        password:"",
        stallClassify:'',
        marketId:'',
        address:"",
        accreditStatus:0,
        enable:1,
        data_enable:true,
        depositBank:'',
        accountName:'',
        account:'',
        pictures:'',
        createBy:'',
        paymentTerms:'乙方在货柜清柜离场并出具《销售账单》（T日）将全部货款应于 T+3 日内向甲方一次性付清'
      },
      formEditData:{
        phoneNumber:'',
        customerName:'',
        customerNum:'',
        customerClassify:'',
        enable:1,
        data_enable:true,
        depositBank:'',
        accountName:'',
        account:'',
        pictures:'',
        createBy:'',
      },
      market_data:[],
      pictures:[],
      rules:{
        phoneNumber:[{
          required: true,
          message: '请输入手机号码',
          trigger: 'blur'
        }],
        password:[{
          required: true,
          message: '请输入登录密码',
          trigger: 'blur'
        }],
        name:[{
          required: true,
          message: '请输入档口名称',
          trigger: 'blur'
        }],
        marketId: [{
          required: true,
          message: '请选择所属市场',
          trigger: 'change'
        }],
        stallType:[{
          required: true,
          message: '请选择档口类型',
          trigger: 'change'
        }],
        paymentTerms:[{
          required: true,
          message: '请输入付款条款',
          trigger: 'blur'
        }]
      },
      ids:[],
      list_params:{
        pageNum: 1,
        pageSize: 10,
      },
      list_total:0,
    }
  },
  created() {
    this.getList()
    this.getMarketList()
    this.getAreaTree()
  },
  methods:{
    getAreaTree(){
      getAreaTree().then(res => {
        console.log(res)
        this.area_data = res.data;
      })
    },
    getMarketList(){
      marketList({is_page:0}).then(res => {
        this.market_data = res.rows;
        console.log(res.rows)
      })
    },
    getList(){
      list(this.list_params).then(res => {
        this.table_data = res.rows;
        this.list_total = res.total;
        console.log(res.rows)
      })
    },
    addCustom(){
      this.formData = {
        paymentTerms: '乙方在货柜清柜离场并出具《销售账单》（T日）将全部货款应于 T+3 日内向甲方一次性付清'
      }
      this.add_custom_dialog_show = true;
    },
    close(){
      this.$refs['elForm'].resetFields();
      this.add_custom_dialog_show = false;
    },
    handleConfirm(){

        this.$refs['elForm'].validate((valid)=>{
          if (valid){
            this.formData.createBy = store.getters.user_id;
            console.log(this.formData)
            if (this.formData.city){
              let city = this.formData.city
              this.formData = {
                ...this.formData,
                province:city[0],
                city:city[1],
                county:city[2]
              }
            }

            this.formData = {
              ...this.formData,
              xnfSettleAccountsList:[{
                depositBank:this.formData.depositBank?this.formData.depositBank:'',
                accountName:this.formData.accountName?this.formData.accountName:'',
                account:this.formData.account?this.formData.account:'',
              }]
            }
            if (this.formData.id){
              update(this.formData).then(res=>{
                this.getList()
                this.add_custom_dialog_show = false
                this.pictures = []
              })
            }else{

              add(this.formData).then(res=>{
                this.getList()
                this.pictures = []
                this.add_custom_dialog_show = false
              })
            }
            this.$refs['elForm'].resetFields();
          }
        });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    handleExport() {
      this.download('xnf/customer/export', {
        ...this.queryParams
      }, `customer${new Date().getTime()}.xlsx`)
    },
    handleEnable(enable){
      console.log(this.ids);
      if (this.ids.length == 0){
        this.$message({
          message: '请选择要操作的数据',
          type: 'warning'
        });
        return
      }
      handleEnable(this.ids,enable).then(res => {
        this.getList()
      })
    },
    editInfo(row){
      let id = row.id;
      detail(id).then(res => {
        this.formData = {
          ...res.data,
          customerClassify:(res.data.customerClassify)+'',
          city:[res.data.province,res.data.city,res.data.county]
        };
        if (res.data.xnfSettleAccountsList.length > 0){
          this.formData = {
            ...this.formData,
            depositBank:res.data.xnfSettleAccountsList[0].depositBank,
            accountName:res.data.xnfSettleAccountsList[0].accountName,
            account:res.data.xnfSettleAccountsList[0].account
          }
        }
        // this.formEditData.data_enable = this.formEditData.enable == 0
        // this.formEditData.customerClassify = (this.formEditData.customerClassify)+''
        this.add_custom_dialog_show = true
      })
    },
    field101BeforeUpload(){

    },
    field101Success(e){
      console.log(e)
      let file = {
        name:e.originalFilename,
        url:e.url
      }
      this.formData = {
        ...this.formData,
        pictures:JSON.stringify(file)
      }
    },
    field101Remove(){
      this.formData = {
        ...this.formData,
        pictures:''
      }
    },
    handleQuery(){
      this.getList()
    },
    resetQuery() {
      this.$refs.searchForm.resetFields();
      this.list_params = {}
      this.getList()
    },
    del_item({id}){
      del(id).then(res=>{
        this.getList()
      })
    },
    accredit({id,accreditStatus}){
      let status = accreditStatus == 0?1:0
      handleAccredit([id],status).then(res => {
        this.getList()
      })
    }
  }
}
</script>

<style scoped>

</style>
